﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using H2.NET.Web.Workflow.Services;
using H2.NET.Business.Core;
using System.Text;
using H2.NET.Web.Workflow.DwzCode;
using H2.NET.Common;
using H2.NET.Web.Workflow.Helpers;

namespace H2.NET.Web.Management.Account
{
    public partial class Create : BasePage
    {

        private readonly AccountService _accountService = new AccountService();
        private readonly RoleService _roleService = new RoleService();

        private int _id;

        protected void Page_Load(object sender, EventArgs e)
        {
            var action = Request.QueryString["action"];


            if (action == "save")
            {
                var user = new t_mdc_Account
                {
                    Username = Request.Form["associateName"],
                    LastLoginTime = DateTime.Now,
                    LastLoginIp = AksRequest.GetIP(),
                    Status = Convert.ToBoolean(Request.Form["Status"])
                };

                if (_accountService.ExistsByName(user.Username))
                {
                    ErrorMsg("该用户名已存在！");
                    return;
                }

                this._id = _accountService.Add(user);
                var roles = Request.Form["roles"] ?? "";
                _roleService.SetRoles(this._id, roles.Split(',').ToArray());
                SuccessMsg("AccountIndex");
            }
            else
            {
                var roles = ConvertHelper<t_mdc_Role>.ConvertToList(_roleService.GetList("").Tables[0]);
                var options = new StringBuilder();
                foreach (var role in roles)
                {
                    options.AppendLine("<option value='" + role.Id + "'>" + role.Name + "</option>");
                }
                l_options.Text = options.ToString();
            }
        }
    }
}